import * as vscode from 'vscode'
import { RecordData, TagConfig } from '../types'
import { getCurrentWorkspacePath } from '../utils/workspace'
import { autoSaveFile } from '../utils/fileManager'

// 默认标签配置
const DEFAULT_TAG_CONFIG: TagConfig = {
  maxTags: 6,
  maxTagLength: 20,
  allowedCharacters: /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/
}

export class RecordService {
  constructor(private context: vscode.ExtensionContext) {}

  // 获取当前工作区的记录
  getWorkspaceRecords(): RecordData[] {
    const workspacePath = getCurrentWorkspacePath()
    if (!workspacePath) return []

    const allRecords = this.context.globalState.get('codememo_workspace_records', {}) as Record<string, RecordData[]>
    const records = allRecords[workspacePath] || []

    // 确保标签字段兼容性 - 为旧记录添加空标签数组
    return records.map(record => ({
      ...record,
      tags: record.tags || []
    }))
  }

  // 更新当前工作区的记录
  updateWorkspaceRecords(records: RecordData[]): void {
    const workspacePath = getCurrentWorkspacePath()
    if (!workspacePath) return

    const allRecords = this.context.globalState.get('codememo_workspace_records', {}) as Record<string, RecordData[]>
    allRecords[workspacePath] = records
    this.context.globalState.update('codememo_workspace_records', allRecords)
  }

  // 创建新记录
  createRecord(data: any): RecordData {
    const workspacePath = getCurrentWorkspacePath()
    if (!workspacePath) {
      throw new Error('没有打开的工作区')
    }

    // 验证和处理标签
    const validatedTags = this.validateAndProcessTags(data.tags || [])

    return {
      id: Date.now(),
      problem: data.problem,
      solution: data.solution,
      filePath: data.filePath,
      codeSnippet: data.codeSnippet,
      lineRange: data.lineRange,
      createdAt: new Date().toISOString(),
      workspacePath,
      tags: validatedTags // 新增：标签字段
    }
  }

  // 保存记录
  saveRecord(record: RecordData): void {
    const records = this.getWorkspaceRecords()
    records.push(record)
    this.updateWorkspaceRecords(records)
  }

  // 更新记录
  async updateRecord(recordId: number, updates: Partial<RecordData>): Promise<RecordData | null> {
    const records = this.getWorkspaceRecords()
    const recordIndex = records.findIndex(r => r.id === recordId)

    if (recordIndex === -1) {
      return null
    }

    // 如果更新包含标签，需要验证
    if (updates.tags) {
      updates.tags = this.validateAndProcessTags(updates.tags)
    }

    // 更新记录
    const updatedRecord = { ...records[recordIndex], ...updates }
    records[recordIndex] = updatedRecord

    // 保存更新
    this.updateWorkspaceRecords(records)

    return updatedRecord
  }

  // 删除记录
  deleteRecord(recordId: number): boolean {
    const records = this.getWorkspaceRecords()
    const index = records.findIndex(r => r.id === recordId)

    if (index === -1) return false

    const record = records[index]
    records.splice(index, 1)
    this.updateWorkspaceRecords(records)

    return true
  }

  // 查找记录
  findRecord(recordId: number): RecordData | null {
    const records = this.getWorkspaceRecords()
    return records.find(r => r.id === recordId) || null
  }

  // 数据迁移
  migrateRecordsData(): void {
    const oldRecords = this.context.globalState.get('codememo_records', []) as any[]

    if (oldRecords.length > 0) {
      const workspacePath = getCurrentWorkspacePath()
      if (workspacePath) {
        const allRecords = this.context.globalState.get('codememo_workspace_records', {}) as Record<string, RecordData[]>

        if (!allRecords[workspacePath]) {
          allRecords[workspacePath] = oldRecords.map(record => ({
            ...record,
            workspacePath,
            tags: record.tags || [] // 迁移时添加空标签数组
          }))

          this.context.globalState.update('codememo_workspace_records', allRecords)
          this.context.globalState.update('codememo_records', undefined)

          console.log('数据迁移完成，已添加标签支持')
        }
      }
    }
  }

  // 新增：验证和处理标签
  private validateAndProcessTags(tags: string[]): string[] {
    if (!Array.isArray(tags)) {
      console.warn('标签必须是数组格式')
      return []
    }

    const processedTags: string[] = []

    for (const tag of tags) {
      // 确保是字符串并去除前后空格
      const cleanTag = String(tag).trim()

      // 跳过空标签
      if (!cleanTag) continue

      // 检查标签长度
      if (cleanTag.length > DEFAULT_TAG_CONFIG.maxTagLength) {
        console.warn(`标签 "${cleanTag}" 超过最大长度限制 ${DEFAULT_TAG_CONFIG.maxTagLength}`)
        continue
      }

      // 检查字符规则
      if (DEFAULT_TAG_CONFIG.allowedCharacters && !DEFAULT_TAG_CONFIG.allowedCharacters.test(cleanTag)) {
        console.warn(`标签 "${cleanTag}" 包含不允许的字符`)
        continue
      }

      // 避免重复标签
      if (!processedTags.includes(cleanTag)) {
        processedTags.push(cleanTag)
      }

      // 检查数量限制
      if (processedTags.length >= DEFAULT_TAG_CONFIG.maxTags) {
        console.warn(`标签数量已达到最大限制 ${DEFAULT_TAG_CONFIG.maxTags}`)
        break
      }
    }

    return processedTags
  }

  // 新增：获取所有标签（用于标签建议等功能）
  getAllTags(): string[] {
    const records = this.getWorkspaceRecords()
    const allTags = new Set<string>()

    records.forEach(record => {
      if (record.tags) {
        record.tags.forEach(tag => allTags.add(tag))
      }
    })

    return Array.from(allTags).sort()
  }

  // 新增：根据标签搜索记录
  findRecordsByTag(tag: string): RecordData[] {
    const records = this.getWorkspaceRecords()
    return records.filter(record => record.tags && record.tags.includes(tag))
  }

  // 新增：获取标签统计信息
  getTagStatistics(): Record<string, number> {
    const records = this.getWorkspaceRecords()
    const tagStats: Record<string, number> = {}

    records.forEach(record => {
      if (record.tags) {
        record.tags.forEach(tag => {
          tagStats[tag] = (tagStats[tag] || 0) + 1
        })
      }
    })

    return tagStats
  }
}
